using ImoviesBlazor.Shared.Dtos;
using System.Text.Json;
using System.Net.Http.Json;
using ImoviesBlazor.Shared.Utils;
using Microsoft.JSInterop;


namespace ImoviesBlazor.Client.Pages
{
    public partial class Movie
    {
        //[Inject]
        //public HttpClient HttpClient { get; set; }
        //[Inject]
        //public IJSRuntime Js { get; set; }


        // 所有年份数据
        public List<uint> totalYears = new List<uint>();
        // 视频列表数据
        public List<MovieDataList> movieDataList = new List<MovieDataList>();
        // 年度点评数据
        public List<AnnualReviewDto> annualReviews = new List<AnnualReviewDto>();

        /// <summary>
        /// 视频播放链接列表数据
        /// </summary>
        public Dictionary<string, List<MovieVlinkDto>> vlinkListMap = new Dictionary<string, List<MovieVlinkDto>>();
        /// <summary>
        /// 播放链接面板是否展开
        /// </summary>
        public Dictionary<string, bool> vlinksIsExpand = new Dictionary<string, bool>();

        // 页大小
        public int pageSize = 12;
        // 当前页
        public int currentPage = 1;
        // 总页数
        public int totalPage;
        // 视频链接是否显示控制按钮是否选中
        public bool showVlinksBtnIsChecked = false;
        // 播放器是否显示
        public bool playerIsVisible = false;
        // 真实播放地址
        public string realPlayUrl = string.Empty;
        // 当前视频名称
        public string currentVideo = string.Empty;
        // 播放器标题
        public string playerTitle = string.Empty;
        // 暂存前一次展开链接列表的视频id
        public string oldVideoId = string.Empty;
        // 暂存前一次需解析视频地址
        public string oldOriginPlayUrl = string.Empty;


        /// <summary>
        /// 顶部年份导航标签随机颜色
        /// </summary>
        /// <returns></returns>
        public string GetTagColor()
        {
            string[] colors = { "#F8BBD0", "#C5CAE9", "#BBDEFB", "#B2EBF2", "#DCEDC8", "#C8E6C9", "#FFECB3", "#E1BEE7" };
            return colors[new Random().Next(colors.Length - 1)];
        }

        /// <summary>
        /// 时间轴标题随机颜色
        /// </summary>
        /// <returns></returns>
        public string GetTimelineTitleColor()
        {
            string[] colors = { "cyan", "green", "pink", "amber", "orange" };
            return colors[new Random().Next(colors.Length - 1)];
        }

        /// <summary>
        /// 调用js进行锚点跳转
        /// </summary>
        /// <param name="anchorName"></param>
        /// <returns></returns>
        public async Task GoAnchor(string anchorName)
        {
            await Js.InvokeVoidAsync("goAnchor", anchorName);
        }

        /// <summary>
        /// 年度评论语
        /// </summary>
        /// <param name="year"></param>
        /// <returns></returns>
        public string GetAnnualReview(uint year)
        {
            return annualReviews.FirstOrDefault(x => x.Year == year)?.Comment ?? "暂无评语";
        }


        /// <summary>
        /// 控制是否显示播放链接
        /// </summary>
        public async Task ShowVlinksBtnClick(string id, string name)
        {
            showVlinksBtnIsChecked = !showVlinksBtnIsChecked;
            // 集数列表不存在或为空时请求接口获取数据
            if ((!vlinkListMap.ContainsKey(id)) || vlinkListMap[id].Count == 0)
            {
                // 获取视频播放链接
                var resp = await HttpClient.GetAsync($"api/movie/vlist/{id}");
                var vlinkList = JsonSerializer.Deserialize<List<MovieVlinkDto>>(await resp.Content.ReadAsStringAsync(),
                new JsonSerializerOptions
                {
                    PropertyNameCaseInsensitive = true,
                    IncludeFields = true,
                }) ?? new List<MovieVlinkDto>();

                // 不为空则存入字典
                if (vlinkList.Count > 0)
                {
                    vlinkListMap.Add(id, vlinkList);
                }
            }
            currentVideo = name;
            if (!vlinksIsExpand.ContainsKey(id))
            {
                // 不存在则添加
                vlinksIsExpand.Add(id, true);
            }
            else
            {
                // 存在则取反
                vlinksIsExpand[id] = !vlinksIsExpand.GetValueOrDefault(id);
            }
        }


        /// <summary>
        /// 获取真实播放地址
        /// </summary>
        /// <param name="url">原url</param>
        public async Task GetRealPlayLink(string name, string url)
        {
            // 真实播放地址为空或需解析地址不等于上次地址时才进行请求
            if (string.IsNullOrEmpty(realPlayUrl) || url != oldOriginPlayUrl)
            {
                // 真实地址解析
                var resp = await HttpClient.PostAsJsonAsync<LinkParseReqParameter>("api/playlink",
                 new LinkParseReqParameter
                 {
                     Vcate = "Movie",
                     OriginUrl = url
                 });
                realPlayUrl = await resp.Content.ReadAsStringAsync();
                oldOriginPlayUrl = url;
            }
            playerTitle = $"正在播放 「{currentVideo}-{name}」";
            playerIsVisible = true;
        }


        /// <summary>
        /// 播放器关闭
        /// </summary>
        public void PlayerCloseAsync()
        {
            realPlayUrl = string.Empty;
            playerTitle = string.Empty;
            playerIsVisible = false;
        }


        /// <summary>
        /// 翻页
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public async Task paginationChangedAsync(int value)
        {
            int oldPage = currentPage;
            currentPage = value;
            if (currentPage != oldPage)
            {
                // 获取视频列表
                var resp = await HttpClient.GetAsync($"api/movie?pageSize={pageSize}&pageNum={currentPage}");
                var resData = JsonSerializer.Deserialize<PaginationList<MovieDataList>>(await resp.Content.ReadAsStringAsync(),
                 new JsonSerializerOptions
                 {
                     PropertyNameCaseInsensitive = true,
                     IncludeFields = true,
                 });
                if (resData != null)
                {
                    var data = resData.Data;
                    movieDataList.Concat(data);

                    foreach (var item in data)
                    {
                        foreach (var t in item.List)
                        {
                            vlinksIsExpand.Add(t.Id, false);
                        }
                    }
                }
            }
        }


        /// <summary>
        /// 生命周期，加载完毕
        /// </summary>
        /// <returns></returns>
        protected override async Task OnInitializedAsync()
        {
            // 获取所有年份
            totalYears = await HttpClient.GetFromJsonAsync<List<uint>>("api/movie/years") ?? new List<uint>();
            // 获取视频列表
            var resp = await HttpClient.GetAsync($"api/movie?pageSize={pageSize}&pageNum={currentPage}");
            var resData = JsonSerializer.Deserialize<PaginationList<MovieDataList>>(await resp.Content.ReadAsStringAsync(),
             new JsonSerializerOptions
             {
                 PropertyNameCaseInsensitive = true,
                 IncludeFields = true,
             });
            if (resData != null)
            {
                movieDataList = resData.Data;
                int totalCount = resData.Total;
                totalPage = (totalCount + pageSize - 1) / pageSize;
                if (totalCount == 0)
                {
                    totalPage = 1;
                }

                //初始化集数是否显示的字典
                foreach (var item in movieDataList)
                {
                    foreach (var t in item.List)
                    {
                        vlinksIsExpand.Add(t.Id, false);
                    }
                }
            }

            // 获取年度点评
            var resp2 = await HttpClient.GetAsync($"api/AnnualReview/{(uint)AnnualReviewsVideoCate.Movie}");
            annualReviews = JsonSerializer.Deserialize<List<AnnualReviewDto>>(await resp2.Content.ReadAsStringAsync(),
               new JsonSerializerOptions
               {
                   PropertyNameCaseInsensitive = true,
                   IncludeFields = true,
               }) ?? new List<AnnualReviewDto>();
            await base.OnInitializedAsync();
        }
    }
}